<template>
  <el-dialog
    title="会员充值"
    v-model="visible"
    width="500px"
    @closed="resetForm"
  >
    <el-form :model="form" :rules="rules" ref="formRef">
      <el-form-item label="充值金额" prop="amount">
        <el-input-number
          v-model="form.amount"
          :min="1"
          :precision="2"
          placeholder="请输入充值金额"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="备注">
        <el-input
          v-model="form.remark"
          type="textarea"
          :rows="3"
          placeholder="请输入充值备注（可选）"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="exit">取消</el-button>
      <el-button
        type="primary"
        :loading="loading"
        @click="submitForm">
        确认充值
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { rechargeVip } from '@/api/customerVip'

const props = defineProps({
  memberId: {
    type: String,
    required: true
  }
})

const emit = defineEmits(['recharged'])

const form = reactive({
  amount: 0,
  remark: ''
})

const rules = {
  amount: [
    { required: true, message: '请输入充值金额', trigger: 'blur' },
    { type: 'number', min: 0.01, message: '金额必须大于0', trigger: 'change' }
  ]
}

const visible = ref(false)
const loading = ref(false)
const formRef = ref()

const resetForm = () => {
  form.amount = 0
  form.remark = ''
}

const submitForm = async () => {
  try {
    loading.value = true
    await formRef.value.validate()

    const res = await rechargeVip({
      id: props.memberId,
      money: form.amount,
      desc: form.remark
    })

    if(res.code === 0) {
      ElMessage.success('充值成功')
      emit('recharged')
      visible.value = false
    }
  } catch (error) {
    console.error('充值失败:', error)
    ElMessage.error('充值失败')
  } finally {
    loading.value = false
  }
}
const exit = () => {

      emit('recharged')

}

defineExpose({
  visible
})
</script>
